package com.gene.service.impl;

import com.gene.mapper.UpmsAddressMapper;
import com.gene.pojo.UpmsAddress;
import com.gene.pojo.UpmsAddressExample;
import com.gene.service.IUpmsAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UpmsAddressServiceImpl implements IUpmsAddressService{
    @Autowired
    private UpmsAddressMapper upmsAddressMapper;


    @Override
    public List<UpmsAddress> query(UpmsAddress upmsAddress) {
        UpmsAddressExample example=new UpmsAddressExample();
        UpmsAddressExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(upmsAddress.getUserId());
        List<UpmsAddress> list = upmsAddressMapper.selectByExample(example);
        return list;
    }

    @Override
    public UpmsAddress selectId(UpmsAddress upmsAddress) {
        UpmsAddress upmsAddress1 = upmsAddressMapper.selectByPrimaryKey(upmsAddress.getAddressId());
        return upmsAddress1;
    }

    @Override
    public UpmsAddress selectDefau(UpmsAddress upmsAddress) {
        UpmsAddress u=upmsAddressMapper.defau(upmsAddress);
        return u;
    }

    @Override
    @Transactional
    public boolean defau(UpmsAddress upmsAddress) {
        //把默认地址查询出来
        UpmsAddress u= upmsAddressMapper.defau(upmsAddress);

        int a=1;
        if(null != u){//有选择默认地址
            u.setIsdefault((byte) 0);
            a=upmsAddressMapper.updateByPrimaryKeySelective(u);
        }
        if(a ==1){
            int b=upmsAddressMapper.updateByPrimaryKeySelective(upmsAddress);
            if( b==1){
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean add(UpmsAddress upmsAddress) {
        //如果是第一次新增，设置为默认地址
        UpmsAddressExample example=new UpmsAddressExample();
        UpmsAddressExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(upmsAddress.getUserId());
        List<UpmsAddress> list = upmsAddressMapper.selectByExample(example);
        if(list.size()==0){
            upmsAddress.setIsdefault((byte) 1);
        }else{
            upmsAddress.setIsdefault((byte) 0);
        }
        int a=upmsAddressMapper.insert(upmsAddress);
        if(a==1){
            return true;
        }
        return false;
    }

    @Override
    public boolean edit(UpmsAddress upmsAddress) {
        int a=upmsAddressMapper.updateByPrimaryKeySelective(upmsAddress);
        if(a==1){
            return true;
        }
        return false;
    }

    @Override
    public boolean delete(UpmsAddress upmsAddress) {
        int a=upmsAddressMapper.deleteByPrimaryKey(upmsAddress.getAddressId());
        if(a==1){
            return true;
        }
        return false;
    }
}
